<template>
  <div class="vehicle-position">
    <!-- 搜索区域 -->
    <div class="search">
      <h1>车位管理</h1>
      <hr style="border: 1px solid rgb(240, 240, 240)" />
      <Echarts></Echarts>
      <span>车位状态</span>
      <el-select
        v-model="position_status"
        style="width: 200px"
        placeholder="请选择车位状态"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <span>车位编号</span>
      <el-input
        v-model="region_name"
        style="width: 200px; margin-right: 10%"
        placeholder="请输入车位编号"
      />
      <el-button @click="searchVehiclePositions" type="primary">查询</el-button>
      <el-button @click="reset" type="default">重置</el-button>

    </div>

    <!-- 车位列表 -->
    <div class="page">
      <div class="page-header">
        <div class="page-header-left">
          <span>车位列表</span>
        </div>
        <div class="page-header-right">
          <el-button
            type="primary"
            style="margin-top: 1rem"
            @click="to('car/newPosition')"
            >+&nbsp;新建
          </el-button>
          <el-button
            type="default"
            style="margin-top: 1rem; margin-right: 3rem"
            @click="deleteDialog = true"
            >批量删除</el-button
          >
          <el-dialog
            v-model="deleteDialog"
            title="警告"
            width="500"
            align-center
          >
            <span>是否删除选中的信息，该操作不可撤回！</span>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="deleteDialog = false">取消</el-button>
                <el-button type="primary" @click="deleteByIds">
                  确认
                </el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" />
        <el-table-column label="区域" prop="region" />
        <el-table-column label="车位编号" prop="no" />
        <el-table-column label="面积" prop="area" />
        <el-table-column label="楼层" prop="floor" />
        <el-table-column label="车位类型">
          <template #default="{ row }">
            {{
              row.type === "1"
                ? "产权车位"
                : row.type === "2"
                ? "公共车位"
                : "其他车位"
            }}
          </template>
        </el-table-column>
        <el-table-column label="车位状态">
          <template #default="{ row }">
            {{
              row.status === "1"
                ? "闲置"
                : row.status === "2"
                ? "自用"
                : row.status === "3"
                ? "租赁"
                : row.status === "4"
                ? "借出"
                : "其他"
            }}
          </template>
        </el-table-column>
        <el-table-column label="绑定住户" prop="owner" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button @click="openDetailDialog(row.id)" type="text"
              >编辑
            </el-button>
            <el-button
              v-if="row.position_status === '审核中'"
              @click="approveVehiclePosition(row.id)"
              type="text"
              size="small"
              >审核通过
            </el-button>
            <el-button
              v-if="row.position_status === '审核中'"
              @click="rejectVehiclePosition(row.id)"
              type="text"
              size="small"
              >审核不通过
            </el-button>
            <el-button
              @click="deleteVehiclePosition(row.id)"
              type="text"
              size="small"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          style="margin-bottom: 2rem"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import axios from "axios";
import to from "@/utils/to.js";
import router from "@/router";
import { ElMessage } from "element-plus";
import Echarts from "./Echarts2.vue";

const loading = ref(false);
const deleteDialog = ref(false);
const selectRows = ref([]);

const pageSizeOptions = [5, 10, 20];

const tableData = ref([]);
const totalCount = ref(0);
const pageNum = ref(1);
const pageSize = ref(pageSizeOptions[0]);
const position_status = ref("");
const region_name = ref("");
const options = [
  { value: "", label: "全部" },
  { value: "1", label: "闲置" },
  { value: "2", label: "自用" },
  { value: "3", label: "租赁" },
  { value: "4", label: "借出" },
];

const form = reactive({
  region: "",
  no: "",
  area: "",
  floor: "",
  type: "",
  status: "",
  owner: "",
});

const searchVehiclePositions = async () => {
  try {
    loading.value = true;
    const response = await axios.get(
      `http://localhost:8080/vehiclePosition/list`,
      {
        headers: {
          Authorization: localStorage.getItem("token"),
        },
        params: {
          pageNum: pageNum.value,
          pageSize: pageSize.value,
          status: position_status.value,
          region: region_name.value,
        },
      }
    );

    tableData.value = response.data.records;
    totalCount.value = response.data.total;
    loading.value = false;
  } catch (error) {
    console.error("查询车位列表失败:", error);
  }
};

const openDetailDialog = async (id) => {
  router.push({ path: "/backend/car/newPosition", query: { id: id } });
};

const deleteVehiclePosition = async (id) => {
  try {
    await axios.delete(`http://localhost:8080/vehiclePosition/delete`, {
      headers: {
        Authorization: localStorage.getItem("token"),
      },
      params: {
        id: id,
      },
    });
    searchVehiclePositions(); // 重新加载列表
  } catch (error) {
    console.error("删除车位失败:", error);
  }
};

const handleSelectionChange = (selectedRows) => {
  selectRows.value = selectedRows;
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  searchVehiclePositions();
};

const handleCurrentChange = (newPage) => {
  pageNum.value = newPage;
  searchVehiclePositions();
};

const reset = () => {
  region_name.value = ""; // 清空查询条件
  pageNum.value = 1; // 重置为第一页
  pageSize.value = pageSizeOptions[0]; // 重置每页条数为默认值
  searchVehiclePositions(); // 重新查询所有住户数据
};

// 初始化加载
searchVehiclePositions();

const deleteByIds = () => {
  if (selectRows.value.length === 0) {
    ElMessage({
      message: "请选择要删除的信息",
      type: "warning",
    });
    deleteDialog.value = false;
    return;
  }

  const config = {
    url: "http://localhost:8080/vehiclePosition/deleteByIds",
    method: "DELETE",
    headers: {
      Authorization: localStorage.getItem("token"),
    },
    data: selectRows.value.map((item) => item.id),
  };

  const response = axios(config);
  response
    .then((data) => {
      if (data.data.code === 1) {
        ElMessage({
          message: "删除成功",
          type: "success",
        });
        setTimeout(() => {
          searchVehiclePositions();
        }, 2000);
      }
    })
    .catch((error) => {
      console.log(error);
    });
  deleteDialog.value = false;
};
</script>

<style scoped>
.search {
  background-color: white;
  padding-bottom: 2rem;
  height: auto;
  margin-top: 2rem;
}

h1 {
  font-size: 2rem;
  font-weight: 600;
  padding: 2rem 0 10px 4rem;
}

span {
  display: inline-block;
  font-size: 15px;
  margin-top: 2rem;
  margin-left: 3rem;
  margin-right: 1rem;
  height: 24px;
}

.page {
  background-color: white;
  height: auto;
  margin-top: 2rem;
  margin-bottom: 2rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  display: flex;
  margin-top: 2rem;
  justify-content: center;
}
</style>
